package com.midele.goodstuff.data.repository.net_util

import com.midele.goodstuff.MainApplication
import com.midele.goodstuff.util.DataStoreUtils
import com.midele.goodstuff.util.GsonUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl

class SimpleCookieJar : CookieJar {
    private val cookieStore = hashMapOf<String, ArrayList<Cookie>>()

    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
        val host = url.host
        val cookiesForHost = cookieStore[host] ?: arrayListOf()
        cookiesForHost.addAll(cookies)
        cookieStore[host] = cookiesForHost

        MainScope().launch(Dispatchers.IO) {
            DataStoreUtils.saveData<String>(
                MainApplication.instance,
                DataStoreUtils.PrefKeys.COOKIE_DATA,
                GsonUtils.toJson(cookiesForHost)
            )
        }


    }

    override fun loadForRequest(url: HttpUrl): List<Cookie> {
        val host = url.host

        if (cookieStore[host] == null) {

            val cookieStr = DataStoreUtils.readDataBlocking(
                MainApplication.instance,
                DataStoreUtils.PrefKeys.COOKIE_DATA,
                ""
            )

            val cookiesList = GsonUtils.fromJsonList(cookieStr, Cookie::class.java)

            return cookiesList ?: listOf()
        } else {
            return cookieStore[host] ?: listOf()
        }


        //return cookieStore[host] ?: listOf()
    }
}